<?php

namespace app\admin\controller;

use app\admin\model\AuthGroup;
use app\admin\model\Group;
use app\common\model\Leibie;
use app\common\traits\Gate;
use app\common\traits\Page;
use think\Db;
use think\Facade\Cache;
use app\admin\model\Dq;
use app\admin\model\Users;
use app\admin\model\Depar;
use app\admin\model\State;

class User extends Admin
{
    use Page;
    /**
     * 会员显示
     * @return mixed
     */
    public function index()
    {
        $map = [];
        $keyword = input('keyword');
        if(!empty($keyword)){
            if(is_numeric($keyword)){
                $map['id|phone']= (int)$keyword;
            }else{
                $map['username']    =   array('like', '%'.(string)$keyword.'%');
            }
        }
        $log_type = input('depar_id');
        if ($log_type) {
            $map['depar_id'] = $log_type;
        }
        $is_success = input('status');
        if ($is_success) {
            $map['status'] = $is_success;
        }
        $send_id = input('weixinstatus');
        if ($send_id) {
            $map['weixinstatus'] = $send_id;
        }
        $receive_id = input('dq_id');
        if ($receive_id) {
            $map['dq_id'] = $receive_id;
        }
        $group_id = input('group_id');
        if ($group_id) {
            $map['group_id'] = $group_id;
        }
        $data = $this->pageshow('Users',$map,'','juese,depar,dq,group,ygroup',$order='id desc');
        foreach ($data as $vo){
            $vo = $vo->append(['weixinstatus_text','status_text'])->toArray();
            if(!empty($vo['juese'])){
                $a='';
                foreach ($vo['juese'] as $v){
                    $a.=$v['title'].',';
                }
                $vo['title'] = substr( $a, 0,-1);
            }
            $vo['phone'] = hidInfo($vo['phone']);
            $arr[] = $vo;
        }
        $this->assign('Users', $arr);
        $this->assign('map', $map);
        $this->assign('keyword', $keyword);
        $this->getDepar();
        return $this->fetch();
    }

    /**
     * 新增会员
     * @return mixed
     */
    public function add()
    {
        $this->getDepar();
        $authgroup = new AuthGroup();
        $auth_groups    =  $authgroup->getGroups();
        $position = \app\admin\model\Users::getUserPosition();
        $this->assign('auth_groups',$auth_groups);
        $this->assign('position',$position);
        return $this->fetch();
    }

    /**
     * 编辑会员
     * @return mixed
     */
    public function edit()
    {
        input('id') ? $id = input('id') : $this->error('缺少参数');
        if ( is_administrator($id) && !is_administrator() ) {
            $this->error('不能操作超级管理员!');exit;
        }
        $this->getDepar();
        $info = Db::name('Users')->where(['id' => $id])->find();
        $this->assign('info', $info);
        $authgroup = new AuthGroup();
        $auth_groups    =  $authgroup->getGroups();
        $authusers    =  $authgroup->getUserGroup($id);
        $ids = array();
        foreach ($authusers as $value){
            $ids[]      =   $value['group_id'];
        }
        $position = \app\admin\model\Users::getUserPosition();
        $this->assign('auth_groups',$auth_groups);
        $this->assign('auth',$ids);
        $this->assign('position',$position);
        return $this->fetch();
    }

    /**
     *添加会员
     */
    public function addrun()
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/user/index'));
        } else {
            $user = new Users();
            $data = input('post.');
            !empty($data['status']) ?: $data['status'] = 2;
            !empty($data['password'])?$data['password']=md5($data['password']):$data['password']=md5('121314');
            $result = $user->validate(true)->allowField(true)->save($data);
            if (false === $result) {
                // 验证失败 输出错误信息
                $this->error($user->getError());
            } else {
                $authgroup = new AuthGroup();
                $authgroup->addToGroup($result->id,$data['auth_id']);
                $this->success('用户添加成功', url('admin/user/index'));
            }
        }
    }

    /**
     *编辑会员
     */
    public function editrun()
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/user/index'));
        } else {
            $user = new Users();
            $data = input('post.');
            !empty($data['status']) ?: $data['status'] = 2;
            !empty($data['group_id']) ?: $data['group_id'] = null;
            !empty($data['ygroup_id']) ?: $data['ygroup_id'] = null;
            !empty($data['dq_id']) ?: $data['dq_id'] = null;
            if(!empty($data['password'])){
                $data['password']=md5($data['password']);
            }else{
                unset($data['password']);
            }
            $result = $user->allowField(true)->validate('users.edit')->isUpdate(true)->save($data);
            if ($result !== false) {
                $authgroup = new AuthGroup();
                $authgroup->addToGroup($data['id'],$data['auth_id']);
                $this->success('用户修改成功', url('admin/user/index'));
            } else {
                // 验证失败 输出错误信息
                $this->error($user->getError());
            }
        }
    }
    //删除会员
    public function del()
    {
        $id = $this->request->param('id', 0);
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        if (Users::update(['id'=>$id,'status'=>2])) {
            $this->success('禁用成功');
        } else {
           $this->error('禁用失败');
        }
    }

    /**
     *获取部门，门店,用户
     */
    public function getDepar(){
        $depar = Depar::where(['status'=>1])->select();
        $dq    = Dq::where(['status'=>1])->select();
        $group = Group::where(['status'=>1])->select();
        $ygroup = \app\admin\model\Ygroup::where(['status'=>1])->select();
        $this->assign("depar",$depar);
        $this->assign("group",$group);
        $this->assign("ygroup",$ygroup);
        $this->assign("dq",$dq);
    }
    //ajax 获取门店
    public function getgroup(){
        $deparid= input('depar_id');
        $dqid= input('dq_id');
        if(!empty( $dqid)){
            $map['dq_id']=$dqid;
        }
        if(!empty( $deparid)){
            $map['depar_id']=$deparid;
        }
        $data = Group::where($map)->select();
        return json($data);
    }
    //ajax 获取用户
    public function getmendian(){
        $dqid= input('depar_id');
        $map['depar_id']=$dqid;
        $data = Group::where($map)->select();
        return json($data);
    }
    /**
     * 将用户添加到用户组的编辑页面
     */
    public function group(){
        $uid            = input('id',0,'int');
        $authgroup      =  new AuthGroup();
        $user           =  new Users;
        $auth_groups    =  $authgroup->getGroups();
        $user_groups    = $authgroup->getUserGroup($uid);
        $ids = array();
        foreach ($user_groups as $value){
            $ids[]      =   $value['group_id'];
        }
        $nickname       =   $user->getNickName($uid);
        $this->assign('nickname',   $nickname);
        $this->assign('auth_groups',$auth_groups);
        $this->assign('user_groups',implode(',',$ids));
        return $this->fetch();
    }
    /**
     * 将用户添加到用户组,入参uid,group_id
     */
    public function addToGroup(){
        $uid = $this->request->post('uid');
        $gid = $this->request->post('group_id/a');
//        dump($gid);die;
        if( empty($uid) ){
            $this->error('参数有误');
        }
        $AuthGroup =new AuthGroup();
        $user = new Users();
        if(is_numeric($uid)){
            if ( is_administrator($uid) ) {
                $this->error('该用户为超级管理员');
            }
            if( !$user->where(array('id'=>$uid))->find()){
                $this->error('用户不存在');
            }
        }
        if( $gid && !$AuthGroup->checkGroupId($gid)){
            $this->error($AuthGroup->getError());
        }
        if ( $AuthGroup->addToGroup($uid,$gid) ){
            $this->success('操作成功');
        }else{
            $this->error($AuthGroup->getError());
        }
    }

    /**设置个人需要保密的状态和负责的医院页面
     * @return mixed
     */
    public function setStates(){
        $uid = input('id',0,'int');
        $userInfo = Db::name('users')->where(['id'=>$uid])->find();//当前用户
//        $statusdata = Db::name('state')->cache(6000)->select();//获取所有的状态
        $leibie = new Leibie();
        $yiyuan = $leibie->getYiyuan();
        $this->assign('yiyuan',$yiyuan);
//        $this->assign('statedata',$statusdata);
        $this->assign('userinfo',$userInfo);
        return $this->fetch();
    }

    /**
     *  保存设置的状态和医院
     */
    public function saveSetstates(){
        if(!$this->request->isPost())
            $this->error('提交方式错误');
        $data = $this->request->post();
        if( empty($data['id']) ){
            $this->error('参数丢失');
        }else {
//            $data['baomi_states'] = implode(',',$data['baomi_states']);
            $data['own_yiyuan'] = implode(',',$data['own_yiyuan']);
            $res = model('users')->allowField(true)->isUpdate()->save($data);
            if($res){
                $this->success('操作成功');
            }else{
                $this->error(model('users')->getError());
            }
        }

    }

    /**
     * 解绑
     */
    public function jiebang(){
        $id = $this->request->param('id',0);
        if ( empty($id) ) {
            $this->error('id参数丢失!');
        }
        if ( is_administrator($id) ) {
            $this->error('不能操作超级管理员!');exit;
        }
        if(Users::get($id)){
            if(\think\Db::name('users')->where(['id'=>$id])->update(['weixinstatus'=>2,'openid'=>''])){
                $this->success('解绑成功');
            } else {
                $this->error('解绑失败');
            }
        } else {
            $this->error('该用户不存在');
        }
    }


}
